﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Net;
using Share;
using System.Diagnostics;

namespace CtripSOA
{
    public partial class SOASearch : Form
    {
        Contorler controler = new Contorler();
        XmlOpreate xmlopr = new XmlOpreate();
        FileOpreate file = new FileOpreate();
        private string response = "";
        ImageList imageList = new ImageList();
        string root_path = Application.StartupPath + "\\request\\";
        string Config_path = Application.StartupPath + "\\Config\\";
        String configFile = Application.StartupPath + "\\Config\\config.ini";
        int start = 0;
        public SOASearch()
        {
            InitializeComponent();
        }

        private void SOASearch_Load(object sender, EventArgs e)
        {
            //this.updateMethod();
            imageList.Images.Add(Image.FromFile(Application.StartupPath + "\\ico\\37.ico"));
            imageList.Images.Add(Image.FromFile(Application.StartupPath + "\\ico\\file.ico"));
            this.treeView1.ImageList = imageList;
            System.IO.DirectoryInfo rootDir = new DirectoryInfo(root_path);
            xmlopr.getTreeByDirectory(rootDir, this.treeView1.Nodes);
        }

        /*发送请求*/
        public void SendRequest()
        {
            if ("".Equals(this.request_url.Text))
            {
                MessageBox.Show("请选择环境或填写请求地址");
            }
            else
            {
                this.saveFuc();
                response = controler.send_self(this.findParent(this.treeView1.SelectedNode).Text, this.requestType.SelectedIndex, this.request_url, this.requestText.Text, this.proxy_switch.Checked);
                this.responseText.Text = response;
            }
        }


        /*发送请求按钮点击*/
        private void button1_Click(object sender, EventArgs e)
        {
            this.SendRequest();
        }

        private TreeNode findParent(TreeNode n)
        {
            if (n.Parent == null)
            {
                return n;
            }
            else
            {
                return this.findParent(n.Parent);
            }
        }


        private void label1_Click(object sender, EventArgs e)
        {

        }

        /*response另存为点击*/
        private void saveResponse_Click(object sender, EventArgs e)
        {
            
            this.SaveAs();
        }

        public void SaveAs()
        {
            //String context = "Request URL:" +"\r\n" + request_url.Text + "\r\n" + "\r\n" + "Request:" + "\r\n" + requestText.Text + "\r\n" + "\r\n" + "Response:" + "\r\n" + responseText.Text;
            string SCHRequestBody = this.requestText.Text;
            string requestUrl = this.request_url.Text;
            string responseBody = this.responseText.Text;
            int type = 0;

            if (this.fat.Checked)
            {
                type = 1;
            }
            else if (this.uat.Checked)
            {
                type = 2;
            }
            else if (this.pro.Checked)
            {
                type = 3;
            }
            else if (this.selfDefinition.Checked)
            {
                type = 4;
            }

            if (SCHRequestBody != "" || requestUrl!="")
            {
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Filter = "文本文件|*.txt";
                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    string fname = savefile.FileName;
                    //要保存的文件
                    file.saveAsFile(SCHRequestBody, responseBody, requestUrl, type, fname);
                }
            }
        }


        public void clearResponseText()
        {
            if (responseText != null)
            {
                responseText.Clear();
            }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            this.clearResponseText();
        }

        private void search_TextChanged(object sender, EventArgs e)
        {
            this.responseText.SelectAll();
            this.responseText.SelectionBackColor = Color.White;
            this.mark_searchedText(this.responseText, this.searchText.Text);
        }


        private void mark_searchedText(RichTextBox textBox, string text)
        {
            string search_text = text;

            int index = textBox.Find(search_text,
                RichTextBoxFinds.None);
            int startPos = index;
            int nextIndex = -1;

            if (index == -1)
            {
                textBox.SelectAll();
                textBox.SelectionColor = Color.Black;
                return;
            }

            while (nextIndex != startPos)
            {

                textBox.SelectionStart = index;
                textBox.SelectionLength = search_text.Length;
                textBox.SelectionBackColor = Color.Yellow;
                nextIndex = textBox.Find(search_text, index + search_text.Length, RichTextBoxFinds.None);
                if (nextIndex == -1)
                {
                    nextIndex = startPos;
                }

                index = nextIndex;

            }

        }



        private void find_Click(object sender, EventArgs e)
        {
            string search_text = this.searchText.Text;
            string response_text = this.responseText.Text;
            if (search_text == "")
            {
                MessageBox.Show("请输入查询条件");
                searchText.Focus();
            }

            if (response_text != "" && search_text!="")
            {
                if (start < this.responseText.Text.Length + start)
                {
                    start = responseText.Find(search_text, start,
                        RichTextBoxFinds.None);
                }
                else
                {
                    start = responseText.Find(search_text, start + search_text.Length,
                        RichTextBoxFinds.None);
                }

                if (start == -1)
                {
                    start = 0;
                    return;
                }
                else
                {
                    start = start + search_text.Length;
                    this.responseText.Focus();
                }
            }
        }

        private void deletePoint_Click(object sender, EventArgs e)
        {
            treeView1.Nodes.Remove(treeView1.SelectedNode);
        }

        private void editPoint_Click(object sender, EventArgs e)
        {
            treeView1.SelectedNode.BeginEdit();
        }

        private void addPoint_Click(object sender, EventArgs e)
        {

        }

        private void copy_Click(object sender, EventArgs e)
        {
            if (responseText.Text != "")
            {
                Clipboard.SetDataObject(responseText.Text.Trim());
                MessageBox.Show("复制成功");
            }
            else
            {
                MessageBox.Show("没有内容，无法复制");
            }
        }

        private string getRequest()
        {
            String nodepath = treeView1.SelectedNode.FullPath;
            String nodename = treeView1.SelectedNode.Name;

            string text = file.ReadFile(this.root_path + nodepath);

            return text;
        }

        private void fat_CheckedChanged(object sender, EventArgs e)
        {
            if (this.fat.Checked)
            {
                string text = this.getRequest();
                //request_url.Text = xmlopr.LoadXml(text, "//FAT");
                request_url.Text = file.ReadFile(text, "<FAT>", "</FAT>");
            }
        }

        private void uat_CheckedChanged(object sender, EventArgs e)
        {
            if (this.uat.Checked)
            {
                string text = this.getRequest();
                //request_url.Text = xmlopr.LoadXml(text, "//UAT");
                request_url.Text = file.ReadFile(text, "<UAT>", "</UAT>");
            }
        }

        private void ProCheckedChanged(object sender, EventArgs e)
        {
            if (this.pro.Checked)
            {
                string text = this.getRequest();
                //request_url.Text = xmlopr.LoadXml(text, "//PRO");
                request_url.Text = file.ReadFile(text, "<PRO>", "</PRO>");
            }
        }

        private void ResponseTextKeyDown(object sender, KeyEventArgs e)
        {
            string search_text = this.searchText.Text;
            if (e.KeyCode == Keys.F3)
            {
                if (search_text == "")
                {
                    MessageBox.Show("请输入查询条件");
                    searchText.Focus();
                }
                else
                {
                    if (start < this.responseText.Text.Length + start)
                    {
                        start = responseText.Find(search_text, start,
                            RichTextBoxFinds.None);
                    }
                    else
                    {
                        start = responseText.Find(search_text, start + search_text.Length,
                            RichTextBoxFinds.None);
                    }

                    if (start == -1)
                    {
                        start = 0;
                        return;
                    }
                    else
                    {
                        start = start + search_text.Length;
                        this.responseText.Focus();
                    }
                }
            }
        }


        private void TreeView1AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (this.treeView1.SelectedNode.IsSelected)
            {
                string text = this.getRequest();
                //if (!"".Equals(text)) {
                if (fat.Checked)
                {
                    request_url.Text = file.ReadFile(text, "<FAT>", "</FAT>");
                }
                if (uat.Checked)
                {
                    request_url.Text = file.ReadFile(text, "<UAT>", "</UAT>");
                }
                if (pro.Checked)
                {
                    request_url.Text = file.ReadFile(text, "<PRO>", "</PRO>");
                }
                //}
                requestText.Text = file.ReadFile(text, "<SCHBODY>", "</SCHBODY>");
                responseText.Text = file.ReadFile(text, "<SCHRESPONSE>", "</SCHRESPONSE>");
            }
        }

        public void deleteFile_Click(object sender, EventArgs e)
        {
            this.deleteFileFunction();
        }

        public void deleteFileFunction()
        {
            if (MessageBox.Show("删除案例会删除对应的文件，您确定要删除？", "删除确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                if (file.deleteFile(this.root_path + this.treeView1.SelectedNode.FullPath))
                    this.treeView1.SelectedNode.Remove();
                else
                    MessageBox.Show("删除文件出错");
            }
        }
        private void deletFloder_Click(object sender, EventArgs e)
        {
            this.deletFloderFunction();
        }

        public void deletFloderFunction()
        {
            if (MessageBox.Show("删除目录会删除目录及目录下的文件，您确定要删除？", "删除确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                if (file.DeleteFolder(this.root_path + this.treeView1.SelectedNode.FullPath))
                    this.treeView1.SelectedNode.Remove();
                else
                    MessageBox.Show("删除文件夹出错");
            }
        }

        private void addFloder_Click(object sender, EventArgs e)
        {
            this.addFloder();
        }

        public void addFloder()
        {
            if (File.Exists(this.root_path + this.treeView1.SelectedNode.FullPath))
            {
                MessageBox.Show("该节点下面不可创建目录");
            }
            else
            {
                string foldername = file.notExistFolder(this.root_path + this.treeView1.SelectedNode.FullPath, "新建文件夹");

                TreeNode folder_node = new TreeNode(foldername, 0, 0);
                int newNodeIndex = this.treeView1.SelectedNode.Nodes.Add(folder_node);
                file.CreateFolder(this.root_path + this.treeView1.SelectedNode.FullPath, foldername);
                this.treeView1.SelectedNode.Expand();
                this.treeView1.LabelEdit = true;
                this.treeView1.SelectedNode = this.treeView1.SelectedNode.Nodes[newNodeIndex];

                folder_node.BeginEdit();
            }
        }

        private void AddChildPointClick(object sender, EventArgs e)
        {
            this.AddChildPoint();
        }

        public void AddChildPoint()
        {
            if (File.Exists(this.root_path + this.treeView1.SelectedNode.FullPath))
            {
                MessageBox.Show("该节点下面不可创建案例");
            }
            else
            {
                string filename = file.notExistFile(this.root_path + this.treeView1.SelectedNode.FullPath, "新建文件.txt");

                TreeNode file_node = new TreeNode(filename, 1, 1);
                int newNodeIndex = this.treeView1.SelectedNode.Nodes.Add(file_node);
                file.CreateFile(this.root_path + this.treeView1.SelectedNode.FullPath, filename);

                this.treeView1.SelectedNode.Expand();

                this.treeView1.LabelEdit = true;
                this.treeView1.SelectedNode = this.treeView1.SelectedNode.Nodes[newNodeIndex];

                file_node.BeginEdit();
            }
        }
        private void TreeView1AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (e.Label != null)
            {
                if (e.Label.Length > 0)
                {
                    if (File.Exists(this.root_path + this.treeView1.SelectedNode.FullPath))
                    {
                        this.treeView1.LabelEdit = false;
                        if (!file.modifyFileName(this.root_path + this.treeView1.SelectedNode.FullPath,
                                           this.root_path + this.treeView1.SelectedNode.Parent.FullPath + "\\" + e.Label))
                        {
                            MessageBox.Show("存在同名的案例，请更换案例名");
                            e.CancelEdit = true;
                        }
                    }
                    else
                    {
                        this.treeView1.LabelEdit = false;
                        if (!file.modifyFolderName(this.root_path + this.treeView1.SelectedNode.FullPath,
                                           this.root_path + this.treeView1.SelectedNode.Parent.FullPath + "\\" + e.Label))
                        {
                            MessageBox.Show("存在同名的目录，请更换目录名");
                            e.CancelEdit = true;
                        }
                    }
                }
                else
                {
                    e.CancelEdit = true;
                    e.Node.BeginEdit();
                }
            }
        }
        private void SaveRequestClick(object sender, EventArgs e)
        {      
                this.saveFuc();
        }

        public void saveFuc()
        {
            string SCHRequestBody = this.requestText.Text;
            string requestUrl = this.request_url.Text;
            string responseBody = this.responseText.Text;

            string save_path = this.root_path + this.treeView1.SelectedNode.FullPath;

            int type = 0;

            if (this.fat.Checked)
            {
                type = 1;
            }
            else if (this.uat.Checked)
            {
                type = 2;
            }
            else if (this.pro.Checked)
            {
                type = 3;
            }
            else if (this.selfDefinition.Checked)
            {
                type = 4;
            }

            if (SCHRequestBody != "" || requestUrl!="")
            {
                file.saveFile(SCHRequestBody, responseBody, requestUrl, type, save_path);
            }
         
        }


        private void treeView1_DoubleClick(object sender, EventArgs e)
        {

            this.Rename();
        }

        public void Rename()
        {
            treeView1.LabelEdit = true;
            treeView1.SelectedNode.BeginEdit();
        }

        private void searchText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3)
            {
                find_Click(sender, e);

            }
        }

		/*
		 * 自动更新代码
        private void checkUpdate_Click(object sender, EventArgs e)
        {
            //this.updateFunction();
            if (this.updateFunction()) {
            	Process.Start(@"E:\\CtripSOA源文件\\Update.Core\\bin\\Debug\\Update.Core.exe", @"ftp://172.16.125.38/CtripSOA.exe E:\CtripSOA.exe");
            
           		ExeCommand("taskkill /im CtripSOA.exe /f ");
            } else {
            	MessageBox.Show("现在已经是最新版本了～～");
            }
        }

        public bool updateFunction()
        {
            System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(@"E:\CtripSOA源文件\WindowsFormsApplication1\bin\Debug\CtripSOA.exe");
            //此处换成你的WINFORM程序的EXE路径
            String getVersion = fvi.FileVersion;
            int i = string.Compare(getVersion, "3.0.0.0");
            
            if (i < 0)
            {
            	return true;
            }
            
            return false;
        }*/

        private void button2_Click_1(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.Show();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }


        private void 发送ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SendRequest();
        }

        private void 全选toolStripMenuItem_Click(object sender, EventArgs e)
        {
             ((RichTextBox)ctrpMenu1.SourceControl).SelectAll();
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.saveFuc();
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string selectText = ((RichTextBox)ctrpMenu1.SourceControl).SelectedText;
            if (selectText != "")
            {
                Clipboard.SetText(selectText);
            }
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ((RichTextBox)ctrpMenu1.SourceControl).Paste();
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (((RichTextBox)ctrpMenu1.SourceControl).SelectedText.Length > 0)
            {
                ((RichTextBox)ctrpMenu1.SourceControl).Cut();
            }
        }

        private void 撤销toolStripMenuItem_Click(object sender, EventArgs e)
        {         
            ((RichTextBox)ctrpMenu1.SourceControl).Undo();
        }   

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ((RichTextBox)ctrpMenu1.SourceControl).Clear();
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SaveAs();
        }

        private void 恢复toolStripMenuItem_Click(object sender, EventArgs e)
        {
            ((RichTextBox)ctrpMenu1.SourceControl).Redo();
        }

        private void 发送ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.SendRequest();
        }

        private void 添加目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.addFloder();
        }

        private void 添加案例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.AddChildPoint();
        }

        private void 删除目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.deletFloderFunction();
        }

        private void 删除案例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.deleteFileFunction();
        }

        private void 重命名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Rename();
        }

        private void ctrpMenu1_Opened(object sender, EventArgs e)
        {
            //没有选择文本时，复制菜单禁用
            string selectText = ((RichTextBox)ctrpMenu1.SourceControl).SelectedText;
            if (requestText.Text != "" || responseText.Text != "")
            {
                另存为ToolStripMenuItem.Enabled = true;
                
            }
            else
            {
                另存为ToolStripMenuItem.Enabled = false;
            }

            if (((RichTextBox)ctrpMenu1.SourceControl).Text == "")
            {           
                
                全选toolStripMenuItem.Enabled = false;
            }
            else
            {
                
                全选toolStripMenuItem.Enabled = true;
            }

            if (selectText != "")
            {
                复制ToolStripMenuItem.Enabled = true;
                剪切ToolStripMenuItem.Enabled = true;
            }
            else
            {
                复制ToolStripMenuItem.Enabled = false;
                剪切ToolStripMenuItem.Enabled = false;
            }

            //剪切板没有文本内容时，粘贴菜单禁用
            if (Clipboard.ContainsText())
            {
                粘贴ToolStripMenuItem.Enabled = true;
            }
            else
            {
                粘贴ToolStripMenuItem.Enabled = false;
            }
            if (((RichTextBox)ctrpMenu1.SourceControl).CanUndo)
            {
               撤销toolStripMenuItem.Enabled = true;
            }
            else
            {
               撤销toolStripMenuItem.Enabled = false;
            }
            if (((RichTextBox)ctrpMenu1.SourceControl).CanRedo)
            {
                恢复toolStripMenuItem.Enabled = true;
            }
            else
            {
                恢复toolStripMenuItem.Enabled = false;
            }            
        }

		/*
		 *自动更新代码
        public void updateMethod()
        {

            String updateMethod = file.ReadConfig(configFile, "UpdateMethod");
            if (updateMethod == "AutoUpdate")
            {
                autoUpdate.Checked = true;
                checkUpdate.Enabled = false;
            }
            else
            {
                autoUpdate.Checked = false;
                checkUpdate.Enabled = true;
            }
        }
        
        private void autoUpdate_CheckedChanged(object sender, EventArgs e)
        {
            String updateMethod = file.ReadConfig(configFile, "UpdateMethod");
            if (autoUpdate.Checked)
            {

                file.WriteConfig(configFile, updateMethod, "AutoUpdate");
                checkUpdate.Enabled = false;
            }
            else
            {
                file.WriteConfig(configFile, updateMethod, "ManualUpdate");
                checkUpdate.Enabled = true;
            }
        }
        
        //执行命令
        private void ExeCommand(string commandText)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            try
            {
                p.Start();
                p.StandardInput.WriteLine(commandText);
                p.StandardInput.WriteLine("exit");
                //p.StandardOutput.ReadToEnd();
            }
            catch (Exception e)
            {
            	MessageBox.Show(e.ToString());
            }
        }*/
        
        private void RequestTextTextChanged(object sender, EventArgs e)
        {
        	
        }
    }
}
    

